<template>
  <div class="appointment-container">
    <Header />
    <div class="appointment-content">
      <div v-if="doctors.length === 0 && !loading" class="no-data">
        暂无咨询师信息
      </div>
      <div v-if="loading" class="loading-text">
        正在加载咨询师信息...
      </div>

      <div class="filter-section">
        <el-card class="filter-card">
          <div class="filter-title">筛选条件</div>
          <el-form :model="filterForm" label-width="80px">
            <el-form-item label="姓名">
              <el-input
                v-model="filterForm.name"
                placeholder="请输入医生姓名"
                clearable
                @clear="handleFilter"
                @input="handleFilter"
              >
                <template #suffix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="filterForm.sex">
                <el-radio label="">全部</el-radio>
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="咨询方向">
              <el-select v-model="filterForm.skill" placeholder="请选择咨询方向" clearable>
                <el-option
                  v-for="skill in skillOptions"
                  :key="skill.value"
                  :label="skill.label"
                  :value="skill.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <div class="counselor-list" v-loading="loading">
        <el-row :gutter="20">
          <el-col 
            :span="8" 
            v-for="doctor in doctors" 
            :key="doctor.doctorid"
          >
            <el-card class="counselor-card" shadow="hover">
              <div class="counselor-header">
                <el-avatar 
                  :size="80"
                  :src="doctor.avatar ? doctor.avatar : defaultAvatar"
                  class="doctor-avatar"
                />
                <div class="counselor-basic">
                  <h3>{{ doctor.name }}</h3>
                  <p class="counselor-title">{{ doctor.title || '心理咨询师' }}</p>
                  <div class="counselor-tags">
                    <el-tag 
                      v-for="skill in (doctor.skills || [])"
                      :key="skill"
                      size="small"
                      effect="plain"
                    >
                      {{ getSkillLabel(skill) }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <div class="counselor-info">
                <p class="counselor-intro">{{ doctor.introduction }}</p>
                <p class="counselor-email">
                  <el-icon><Message /></el-icon>
                  邮箱：{{ doctor.email }}
                </p>
                <div class="counselor-details">
                  <span class="duration">擅长方向：{{ getSkillLabel(doctor.skill) }}</span>
                </div>
              </div>
              <div class="counselor-footer">
                <el-button type="primary" @click="viewSchedule(doctor)">
                  立即预约
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[6, 9, 12, 15]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <Footer />

    <!-- 预约对话框 -->
    <el-dialog
      v-model="scheduleDialogVisible"
      :title="`${selectedDoctor?.name || ''}的预约时间`"
      width="60%"
    >
      <div v-if="selectedDoctor" class="schedule-content">
        <el-table :data="availableTimeSlots" style="width: 100%">
          <el-table-column label="工作日" width="120">
            <template #default="{ row }">
              {{ weekdays[row.weekday] }}
            </template>
          </el-table-column>
          
          <el-table-column label="时间段" width="200">
            <template #default="{ row }">
              {{ row.begTime }} - {{ row.endTime }}
            </template>
          </el-table-column>
          
          <el-table-column label="可预约人数" width="120">
            <template #default="{ row }">
              {{ row.currentCapacity }}/{{ row.maxCapacity }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                @click="handleAppointment(row)"
              >
                预约
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Message } from '@element-plus/icons-vue'
import Header from '../../components/header.vue'
import Footer from '../../components/footer.vue'
import { getDoctorSchedule, createAppointment, getDoctorByFilter, type Timelist } from '../../api/appointment'
import defaultAvatar from '../../assets/default-avatar.png'

const router = useRouter()
const loading = ref(false)
const doctors = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(9)
const scheduleDialogVisible = ref(false)
const selectedDoctor = ref(null)
const availableTimeSlots = ref<Timelist[]>([])

// 筛选表单数据
const filterForm = ref({
  name: '',
  sex: undefined as undefined | number,
  skill: ''
})

// 专业方向选项
const skillOptions = [
  { label: '情感困扰', value: 'emotion' },
  { label: '学业压力', value: 'study' },
  { label: '职场压力', value: 'work' },
  { label: '家庭关系', value: 'family' },
  { label: '人际关系', value: 'social' },
  { label: '心理障碍', value: 'disorder' },
  { label: '抑郁症', value: 'depression' },
  { label: '焦虑症', value: 'anxiety' },
  { label: '强迫症', value: 'ocd' },
  { label: '失眠', value: 'insomnia' },
  { label: '青少年心理', value: 'youth' },
  { label: '婚恋咨询', value: 'marriage' }
]

const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

// 获取专业方向标签
const getSkillLabel = (skillValue: string) => {
  const skill = skillOptions.find(s => s.value === skillValue)
  return skill ? skill.label : skillValue
}

// 获取咨询师列表
const fetchDoctors = async () => {
  loading.value = true
  try {
    const res = await getDoctorByFilter({
      name: filterForm.value.name || undefined,
      sex: filterForm.value.sex,
      skill: filterForm.value.skill || undefined
    })

    if (res.code === '200') {
      doctors.value = res.data
      total.value = res.total
      console.log('获取到的咨询师列表:', doctors.value)
    } else {
      ElMessage.error(res.msg || '获取咨询师列表失败')
    }
  } catch (error) {
    console.error('获取咨询师列表失败:', error)
    ElMessage.error('获取咨询师列表失败')
  } finally {
    loading.value = false
  }
}

// 查看预约时间
const viewSchedule = async (doctor: any) => {
  selectedDoctor.value = doctor
  try {
    const res = await getDoctorSchedule(doctor.doctorId)
    console.log('获取预约时间响应:', res)
    if (res.code === '200') {
      availableTimeSlots.value = res.data
      scheduleDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取预约时间失败')
    }
  } catch (error) {
    console.error('获取预约时间失败:', error)
    ElMessage.error('获取预约时间失败')
  }
}

// 处理预约
const handleAppointment = async (timeSlot: any) => {
  try {
    const userId = localStorage.getItem('userid')
    const userRole = localStorage.getItem('userRole')

    if (!userId) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    if (userRole === 'doctor') {
      ElMessage.warning('咨询师不能预约咨询')
      return
    }

    const res = await createAppointment({
      clientId: Number(userId),
      doctorId: selectedDoctor.value.doctorId,
      timelistId: timeSlot.timelistId
    })

    if (res.code === 200) {
      ElMessage.success('预约申请已提交')
      scheduleDialogVisible.value = false
      // 刷新预约时间列表
      viewSchedule(selectedDoctor.value)
    } else {
      ElMessage.error(res.msg || '预约失败')
    }
  } catch (error) {
    console.error('预约失败:', error)
    ElMessage.error('预约失败')
  }
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchDoctors()
}

onMounted(() => {
  // 页面加载时立即获取咨询师列表
  fetchDoctors()
  console.log('页面已加载，正在获取咨询师列表...')
})
</script>

<style scoped>
.appointment-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.appointment-content {
  flex: 1;
  width: 800px;
  max-width: 1200px;
  margin: 84px auto 40px;
  padding: 0 20px;
}

.filter-section {
  margin-bottom: 30px;
}

.filter-card {
  padding: 20px;
}

.filter-title {
  font-size: 18px;
  color: #2c3e50;
  margin-bottom: 20px;
  font-weight: bold;
}

.counselor-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.counselor-card:hover {
  transform: translateY(-5px);
}

.counselor-header {
  display: flex;
  margin-bottom: 20px;
}

.counselor-avatar {
  margin-right: 20px;
}

.counselor-basic h3 {
  font-size: 18px;
  color: #2c3e50;
  margin: 0 0 8px;
}

.counselor-title {
  color: #409EFF;
  font-size: 14px;
  margin-bottom: 10px;
}

.counselor-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.counselor-intro {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 15px;
}

.counselor-details {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  color: #666;
}

.duration {
  color: #666;
  font-size: 14px;
}

.counselor-footer {
  text-align: center;
}

.counselor-email {
  color: #666;
  font-size: 14px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.counselor-email .el-icon {
  color: #409EFF;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination) {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.schedule-content {
  max-height: 500px;
  overflow-y: auto;
}

/* 筛选表单样式 */
.filter-card :deep(.el-form-item) {
  margin-bottom: 15px;
}

.filter-card :deep(.el-radio) {
  margin-right: 20px;
}

.filter-card :deep(.el-radio:last-child) {
  margin-right: 0;
}

/* 标签样式 */
.counselor-tags :deep(.el-tag) {
  border-radius: 12px;
  padding: 0 12px;
}

/* 对话框样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-size: 16px;
}

.loading-text {
  text-align: center;
  color: #409EFF;
  padding: 20px 0;
  font-size: 16px;
}
</style>